package com.canglion.ragflow.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.canglion.ragflow.RAGFlowClient;
import com.canglion.ragflow.exception.RAGFlowException;

/**
 * rundreams.blog.csdn.net
 *
 * @Time:2025/9/4
 * @Author: Zihao Zhang
 * @description:
 */

public class WorkflowService {

    private final RAGFlowClient client;

    public WorkflowService(RAGFlowClient client) {
        this.client = client;
    }

    /**
     * 获取工作流列表
     */
    public JSONObject list() {
        String url = client.getBaseUrl() + "/api/v1/workflow/list";

        HttpResponse response = HttpRequest.get(url)
                .header("Authorization", "Bearer " + client.getAuthManager().getAccessToken())
                .timeout(10000)
                .execute();

        if (!response.isOk()) {
            throw new RAGFlowException("Failed to list workflows: " + response.getStatus());
        }

        return JSONUtil.parseObj(response.body());
    }

    /**
     * 触发工作流执行
     */
    public JSONObject run(String workflowId, JSONObject inputParams) {
        String url = client.getBaseUrl() + "/api/v1/workflow/" + workflowId + "/run";

        JSONObject body = JSONUtil.createObj()
                .set("inputs", inputParams);

        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + client.getAuthManager().getAccessToken())
                .header("Content-Type", "application/json")
                .body(body.toString())
                .timeout(15000)
                .execute();

        if (!response.isOk()) {
            throw new RAGFlowException("Run workflow failed: " + response.getStatus() + ", " + response.body());
        }

        return JSONUtil.parseObj(response.body());
    }
}
